package db

import (
	mydb "filestore-server/db/mysql"
	"log"
	"time"
)

// UserFile 用户文件表结构
type UserFile struct {
	UserName string
	FileHash string
	FileName string
	FileSize int64
	UploadAt string
	LastUpdated string

}

//OnUserFileUploadFinished 用户文件关联关系插入
func OnUserFileUploadFinished(username, filehash, filename string, filesize int64) bool {
	stmt, err := mydb.DBConn().Prepare(`insert into tbl_user_file (user_name, file_sha1, file_name, file_size, upload_at) values (?,?,?,?,?)`)
	if err != nil {
		log.Fatal("SQL预编译失败！err: %v", err)
		return false
	}
	defer stmt.Close()

	_, err = stmt.Exec(username, filehash, filename, filesize, time.Now())
	if err != nil {
		log.Fatalf("SQL执行失败！err:%v", err)
		return false
	}

	return true
}

// QueryUserFileMetas 批量查询用户文件信息
func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	stmt, err := mydb.DBConn().Prepare(`select file_sha1, file_name, file_size, upload_at, last_update from tbl_user_file where user_name = ? limit ?`)
	if err != nil {
		log.Fatalf("SQL编译失败！err: %v", err)
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query(username, limit)
	if err != nil {
		log.Fatalf("SQL执行失败！err：%v", err)
		return nil, err
	}

	var userFiles []UserFile
	for rows.Next() {
		ufile := UserFile{}
		err = rows.Scan(&ufile.FileHash, &ufile.FileName, &ufile.FileSize, &ufile.UploadAt, &ufile.LastUpdated)
		if err != nil {
			log.Fatalf("从SQL获取数据失败！err: %v", err)
			break
		}
		userFiles = append(userFiles, ufile)
	}

	return userFiles, nil
}
